package com.weharvest.edu.controller.app;

import com.weharvest.edu.config.FileConfig;
import com.weharvest.edu.config.ProjectConfig;
import com.weharvest.edu.dto.app.AppRecordDto;
import com.weharvest.edu.enums.WechatExceptionEnum;
import com.weharvest.edu.exception.WechatException;
import com.weharvest.edu.service.ReceptionDocumentService;
import com.weharvest.edu.utlis.ResultUtil;
import com.weharvest.edu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * app微信配置控制层
 */
@Controller
@RequestMapping("/app/wechat")
@Slf4j
public class AppWechatController {

    @Resource
    private WxMpService wxMpService;

    @Resource
    private FileConfig fileConfig;

    @Resource
    private ReceptionDocumentService documentService;

    @Resource
    private ProjectConfig projectConfig;

    /**
     * 公众号授权
     *
     * @param resultUrl
     * @param req
     * @return
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam(value = "resultUrl",
            defaultValue = "http://sanly.mynatapp.cc/weharvest/edu/index/#/wechat") String resultUrl,
                            HttpServletResponse req) {
        // 设置回调地址
        String url = projectConfig.getMpAuthorizeUrl() + "/weharvest/wechat/userInfo";
        // 发起微信认证地址
        String redirect = "";
        try {
            redirect = wxMpService.oauth2buildAuthorizationUrl(
                    url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(resultUrl, "UTF-8"));
        } catch (Exception e) {
            log.error("[发起微信公众号授权],{}", e);
            throw new WechatException(WechatExceptionEnum.MP_AUTHORIZE_INVALID);
        }
        return "redirect:" + redirect;
    }

    /**
     * 回调地址
     *
     * @param code
     * @param resultUrl
     * @return
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code, @RequestParam("state") String resultUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[返回微信公众号授权],{}", e);
            throw new WechatException(WechatExceptionEnum.MP_ACCESSTOKEN_ERROR);
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        if (openId.equals("")) {
            log.error("[返回微信公众号授权,openId为空]");
            throw new WechatException(WechatExceptionEnum.MP_OPENID_INVALID);
        }
        //设置cookie
        return "redirect:" + resultUrl + "?openid=" + openId;
    }



    /****************************************Record录音**************************************************/


    /**
     * 兑换jssdk,微信录音
     *
     * @param
     * @return
     */
    @PostMapping("jssdk")
    @ResponseBody
    public ResultVo jssdk(@RequestBody AppRecordDto receptionRecordDto,
                          HttpServletRequest request, HttpServletResponse response) {
        //检验openid
        try {
            //获取ticket
            String ticket = wxMpService.getJsapiTicket();
            WxJsapiSignature wxJsapiSignature =
                    wxMpService.createJsapiSignature(receptionRecordDto.getUrl());
            System.out.println("ticket:" + ticket);
            System.out.println(wxJsapiSignature);
            return ResultUtil.success(wxJsapiSignature);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 下载录音
     *
     * @param appRecordDto
     * @return
     */
    @PostMapping("/record/upload")
    @ResponseBody
    public ResultVo upload(@RequestBody AppRecordDto appRecordDto) {
        documentService.downLoad(appRecordDto, wxMpService);
        return ResultUtil.success();
    }

    /**
     * 提交合成语音
     *
     * @param
     * @return
     */
    public ResultVo submitMergn(@RequestBody AppRecordDto appRecordDto) {

        return null;
    }


    /*************************************************************************************/
}
